package config

import (
	"fmt"
	"github.com/spf13/viper"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

var DB *gorm.DB

type attribute struct {
	driver   string
	url      string
	username string
	password string
	database string
}

type connect struct {
	at  attribute
	dsn string
}

func Mysql() {
	//读取文件
	viper.SetConfigFile("app.yml")
	fmt.Println("正在读取文件app.yml")

	//处理错误
	err := viper.ReadInConfig()
	if err == nil {
		fmt.Println("正在处理读取异常，无异常")
	}

	//属性读取并赋值
	var a = attribute{
		driver:   viper.GetString("mysql.driver"),
		url:      viper.GetString("mysql.url"),
		username: viper.GetString("mysql.username"),
		password: viper.GetString("mysql.password"),
		database: viper.GetString("mysql.database"),
	}
	fmt.Println("正在属性读取并赋值")

	//创建数据库连接
	var con = connect{
		at:  a,
		dsn: a.username + ":" + a.password + "@tcp(" + a.url + ")/" + a.database + "?charset=utf8mb4&parseTime=True&loc=Local",
	}
	fmt.Println("正在创建数据库连接")

	//连接语句
	DB, err = gorm.Open(mysql.Open(con.dsn), &gorm.Config{})
	if err == nil {
		fmt.Println("mysql连接成功")
	}
}
